﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Benchmark.Core.Communication.Data.Interface;

namespace Benchmark.Core.Communication.Data.Stream_Manager
{
   public class StreamManager:IStreamManager,IDisposable 
    {

        // Defines the data protocol for reading and writing strings on our stream 

        private Stream ioStream;
        private UnicodeEncoding streamEncoding;
       


        public StreamManager(Stream ioStream)
        {
            this.ioStream = ioStream;
            streamEncoding = new UnicodeEncoding();
        }

       /// <summary>
       /// Read the yte sequence from stream
       /// </summary>
       /// <returns>array of bytes</returns>
        public byte[] ReadByte()
        {
            int len;
            len = ioStream.ReadByte() * 256;
            len += ioStream.ReadByte();
            byte[] inBuffer = new byte[len];
            ioStream.Read(inBuffer, 0, len);

            return inBuffer;
        }

       /// <summary>
       /// Write the string to stream
       /// </summary>
       /// <param name="outString">String to be written</param>
       /// <returns>buffer length</returns>
        public int WriteByte(string outString)
        {
            byte[] outBuffer = streamEncoding.GetBytes(outString);
            int len = outBuffer.Length;
            if (len > UInt16.MaxValue)
            {
                len = (int)UInt16.MaxValue;
            }
            ioStream.WriteByte((byte)(len / 256));
            ioStream.WriteByte((byte)(len & 255));
            ioStream.Write(outBuffer, 0, len);
            ioStream.Flush();

            return outBuffer.Length + 2;
        }


        public void Dispose()
        {
            this.ioStream.Close();
        }
       /// <summary>
       /// Write the byte
       /// </summary>
       /// <param name="datainBytes">data in bytes to be written to stream</param>
       /// <returns></returns>
        public int WriteByte(byte[] datainBytes)
        {
           byte[] outBuffer = datainBytes;
            int len = outBuffer.Length;
            if (len > UInt16.MaxValue)
            {
                len = (int)UInt16.MaxValue;
            }
            ioStream.WriteByte((byte)(len / 256));
            ioStream.WriteByte((byte)(len & 255));
            ioStream.Write(outBuffer, 0, len);
            ioStream.Flush();

            return outBuffer.Length + 2;
        }
    }
}
